package com.shopping_back.controller;

import com.shopping_back.common.Result;
import com.shopping_back.pojo.dto.MemberPayDTO;
import com.shopping_back.pojo.dto.PayDTO;
import com.shopping_back.pojo.dto.RechargeDTO;
import com.shopping_back.pojo.entity.Sku;
import com.shopping_back.pojo.entity.UserAccount;
import com.shopping_back.service.IPayService;
import com.shopping_back.service.IPointService;
import com.shopping_back.service.IUserProfileService;
import com.shopping_back.service.IUserAccountService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import com.shopping_back.util.JwtUtils;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/api/pay")
@RequiredArgsConstructor
public class PayController {
    private final IPayService payService;
    private final IUserAccountService userAccountService;

    private final IPointService pointService;

    private final IUserProfileService userProfileService;

    private final JwtUtils jwtUtils;
    /**
     * 发起支付宝页面支付，直接返回 HTML Form
     */
    @PostMapping("/alipay")
    public void payWithAlipay(@RequestBody PayDTO dto,
                              HttpServletResponse resp) throws Exception {
        String form = payService.createAlipayPage(dto);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(form);
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    /**
     * 支付宝异步通知
     */
    @PostMapping("/notify")
    public String alipayNotify(HttpServletRequest req) throws Exception {
        System.out.println("支付宝异步通知收到！");
        return payService.handleAlipayNotify(req);
    }

    /**
     * 获取 SKU 详情
     */
    @GetMapping("/sku/{skuId}")
    public Result getSku(@PathVariable Long skuId) {
        Sku sku = payService.getSkuById(skuId);
        return Result.success(sku, null);
    }

    /**
     * 余额支付（若余额不足，返回充值链接）
     */
// PayController.java
    @PostMapping("/balance")
    public Result payWithBalance(@RequestBody PayDTO dto) {

        // 基本校验
//        if (StrUtil.isBlank(dto.getPassword())) {
//            return Result.error("请先输入登录密码");
//        }
//        Long userId = TokenUtil.parse(token).getLong("userId");
        Long userId = 3l;
        //账户信息 & 校验密码
        UserAccount user = userAccountService.getById(userId);
        String hash = encryptPassword(dto.getPassword(), user.getSalt());
        if (!hash.equals(user.getPasswordHash())) {
            return Result.error("密码错误");
        }

        //密码正确 → 继续余额扣款业务
        String rechargeUrl = payService.payWithBalance(dto,userId);

        if (rechargeUrl != null) {
            return Result.success(
                    Map.of("rechargeUrl", rechargeUrl),
                    "余额不足，请先充值");
        }
        return Result.success("余额支付成功");
    }

    //复用的密码函数
    private String encryptPassword(String password, String salt) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
            md.update((password + salt).getBytes());
            byte[] digest = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (Exception e) {
            System.out.println("密码加密失败：" + e.getMessage());
            throw new RuntimeException("密码加密失败", e);
        }
    }


    @GetMapping("/return")
    public void payReturn(HttpServletResponse resp) throws IOException {
        // 跳你首页
        resp.sendRedirect("http://localhost:5173/#/index");
    }

    @GetMapping("/order/{orderSn}")
    public Result getOrderInfo(@PathVariable String orderSn) {
        Map<String,Object> info = payService.getSimpleOrderInfo(orderSn);
        return Result.success(info, null);
    }

    @PostMapping("/recharge")
    public void recharge(@RequestBody RechargeDTO dto,
                         HttpServletRequest request,
                         HttpServletResponse resp) throws Exception {

        // ① 取当前登录用户 ID
        Long userId = jwtUtils.getCurrentUserId(request);

        // ② 生成支付宝表单
        String form = payService.createRechargePage(userId, dto);

        // ③ 直接把 <form> 返回给浏览器渲染
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(form);
        resp.getWriter().flush();
        resp.getWriter().close();

    }

    @PostMapping("/memberPay")
    public void memberPay(@RequestBody MemberPayDTO dto,
                          HttpServletRequest request,
                          HttpServletResponse response) throws Exception {

        // 新增调试日志
        System.out.println("=== 会员支付接口调用 ===");
        System.out.println("接收到的DTO: " + dto);
        System.out.println("Level: " + dto.getLevel() + " (类型: " + (dto.getLevel() != null ? dto.getLevel().getClass().getSimpleName() : "null") + ")");
        System.out.println("Amount: " + dto.getAmount());
        System.out.println("Months: " + dto.getMonths());

        Long uid = jwtUtils.getCurrentUserId(request);
        // 修改：添加了months参数
        String form = payService.createMemberPayPage(uid, dto.getLevel(), dto.getAmount(), dto.getMonths());

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);
        response.getWriter().flush();
    }
}
